<template>
  <div class="app-container">
    <el-card class="mb20">
      <el-form
        ref="saleContractQueryFormRef"
        :model="saleContractQueryForm"
        inline
      >
        <el-form-item label="合同编号" prop="contractNo">
          <el-input
            v-model="saleContractQueryForm.contractNo"
            placeholder="合同编号"
          ></el-input>
        </el-form-item>
        <el-form-item label="订单编号" prop="orderId">
          <el-input
            v-model="saleContractQueryForm.orderId"
            placeholder="订单编号"
          ></el-input>
        </el-form-item>
        <el-form-item label="业务员" prop="salesmanId">
          <el-select
            v-model="saleContractQueryForm.salesmanId"
            placeholder="业务员"
          >
            <el-option
              v-for="item in salesManList"
              :key="item.name"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="客户名称" prop="customerId">
          <el-select
            v-model="saleContractQueryForm.customerId"
            placeholder="客户名称"
          >
            <el-option
              v-for="item in customerList"
              :key="item.name"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="交货日期" prop="deliverAttr">
          <el-date-picker
            v-model="saleContractQueryForm.deliveryAttr"
            type="daterange"
            range-separator="至"
            start-placeholder="开始月份"
            end-placeholder="结束月份"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="送货方式" prop="deliveryMethod">
          <el-select
            v-model="saleContractQueryForm.deliveryMethod"
            placeholder="送货方式"
          >
            <el-option value="快递">快递</el-option>
            <el-option value="物流">物流</el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="签订日期" prop="signAttr">
          <el-date-picker
            v-model="saleContractQueryForm.signAttr"
            type="daterange"
            range-separator="至"
            start-placeholder="开始月份"
            end-placeholder="结束月份"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="申请人" prop="applyUser">
          <el-select
            v-model="saleContractQueryForm.applyUser"
            placeholder="请选择申请人"
          >
            <el-option
              v-for="item in userList"
              :key="item.id"
              :label="item.realName"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="申请时间" prop="applyAttr">
          <el-date-picker
            v-model="saleContractQueryForm.applyAttr"
            type="daterange"
            range-separator="至"
            start-placeholder="开始月份"
            end-placeholder="结束月份"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="申请状态" prop="applyStatus">
          <el-select
            v-model="saleContractQueryForm.applyStatus"
            placeholder="请选择申请状态"
          >
            <el-option label="未提交" value="未提交"></el-option>
            <el-option label="待审核" value="待审核"></el-option>
            <el-option label="已审核" value="已审核"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="审核人" prop="approveUser">
          <el-select
            v-model="saleContractQueryForm.approveUser"
            placeholder="请选择审核人"
          >
            <el-option
              v-for="item in userList"
              :key="item.id"
              :label="item.realName"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="审核时间" prop="approveAttr">
          <el-date-picker
            v-model="saleContractQueryForm.approveAttr"
            type="daterange"
            range-separator="至"
            start-placeholder="开始月份"
            end-placeholder="结束月份"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="审核状态" prop="approveStatus">
          <el-select
            v-model="saleContractQueryForm.approveStatus"
            placeholder="请选择审核状态"
          >
            <el-option label="通过" value="通过"></el-option>
            <el-option label="驳回" value="驳回"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getSaleContractList"
            >查询</el-button
          >
          <el-button @click="resetSaleContractForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card>
      <el-button @click="OpenAddSaleContractDialog">新增</el-button>
      <el-button @click="DelSaleContractMany">删除</el-button>
      <el-table :data="saleContractList" @selection-change="selectionChange">
        <el-table-column type="selection"></el-table-column>
        <el-table-column
          v-for="item in saleContractColumn"
          :key="item.prop"
          :label="item.label"
          :prop="item.prop"
        ></el-table-column>
        <el-table-column label="操作" v-slot="{ row }" width="280px">
          <div>
            <el-button
              size="mini"
              type="success"
              @click="addSaleDeliveryList(row.id)"
              >生成发货单</el-button
            >
            <el-button
              type="primary"
              size="mini"
              @click="OpenEditSaleContractDialog(row)"
              >修改</el-button
            >
            <el-button
              size="mini"
              type="danger"
              @click="DelSaleContractD(row.id)"
              >删除</el-button
            >
          </div>
        </el-table-column>
      </el-table>
      <el-pagination
        style="display: flex; justify-content: right"
        @size-change="SaleContractLimitChange"
        @current-change="SaleContractPageChange"
        :current-page="saleContractPager.page"
        :page-sizes="[2, 10, 30, 40]"
        :page-size="saleContractPager.limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="saleContractPager.total"
      >
      </el-pagination>
    </el-card>

    <!-- 修改销售合同对话框 -->
    <el-dialog
      center
      :visible.sync="saleContractEditDialogVisible"
      :close-on-click-modal="false"
      :title="title"
      width="1400px"
      @close="closeEditSaleContractDialog"
    >
      <el-form
        :model="doEditSaleContractForm"
        ref="doEditSaleContractFormRef"
        inline
      >
        <el-form-item label="订单编号" prop="orderNo" required>
          <el-input
            v-model="doEditSaleContractForm.orderNo"
            placeholder="订单编号"
            disabled
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="OpenSaleOrderDialog"
            >选择</el-button
          >
        </el-form-item>
        <el-form-item label="送货方式" prop="deliveryMethod" required>
          <el-select
            v-model="doEditSaleContractForm.deliveryMethod"
            placeholder="送货方式"
          >
            <el-option label="快递" value="快递"></el-option>
            <el-option label="物流" value="物流"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="收货地址" prop="deliveryAddress" required>
          <el-input
            v-model="doEditSaleContractForm.deliveryAddress"
            placeholder="收货地址"
          ></el-input>
        </el-form-item>
        <el-form-item label="联系人" prop="contact" required>
          <el-input
            v-model="doEditSaleContractForm.contact"
            placeholder="联系人"
          ></el-input>
        </el-form-item>
        <el-form-item label="联系方式" prop="phone" required>
          <el-input
            v-model="doEditSaleContractForm.phone"
            placeholder="联系方式"
          ></el-input>
        </el-form-item>
        <el-form-item label="签订日期" prop="signDate" required>
          <el-date-picker
            v-model="doEditSaleContractForm.signDate"
            type="date"
            placeholder="签订日期"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            style="width: 400px"
            v-model="doEditSaleContractForm.remark"
            type="textarea"
            placeholder="备注"
            resize="none"
            :rows="3"
          ></el-input>
        </el-form-item>
      </el-form>
      <el-divider></el-divider>
      <div>
        <el-button size="mini" type="success" @click="AddDetail"
          >添加</el-button
        >
      </div>
      <el-table :data="detailList">
        <el-table-column v-slot="{ $index }">
          {{ $index + 1 }}
        </el-table-column>
        <el-table-column v-slot="{ row, $index }" width="200px">
          {{ row.material.name }}
          <el-button type="primary" @click="SelectMaterial($index)"
            >选择</el-button
          >
        </el-table-column>
        <el-table-column
          v-for="item in detailColumn"
          :key="item.prop"
          :label="item.label"
          :prop="item.prop"
          :width="item.width"
        >
          <template v-slot="{ row }" v-if="item.prop == 'price'">
            <el-input-number
              size="mini"
              type="number"
              v-model="row.price"
            ></el-input-number>
          </template>
          <template v-slot="{ row }" v-else-if="item.prop == 'quantity'">
            <el-input-number
              size="mini"
              :min="1"
              v-model="row.quantity"
            ></el-input-number>
          </template>
          <template v-slot="{ row }" v-else-if="item.prop == 'amount'">
            {{ (row.amount = row.price * row.quantity) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" v-slot="{ $index }" width="280px">
          <div>
            <el-button
              type="primary"
              size="mini"
              @click="AddDetailEmpty($index)"
              >新增</el-button
            >
            <el-button size="mini" type="danger" @click="DelDetailList($index)"
              >删除</el-button
            >
          </div>
        </el-table-column>
      </el-table>
      <template #footer>
        <div>
          <el-button @click="closeEditSaleContractDialog">取消</el-button>
          <el-button type="primary" @click="EditSaleContract">保存</el-button>
          <el-button type="primary" @click="EditSaleContract">提交</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 选择销售订单对话框 -->
    <el-dialog
      center
      title="选择销售订单"
      :visible.sync="saleOrderVisible"
      :close-on-click-modal="false"
    >
      <el-card class="mb20">
        <el-form :model="saleOrderQueryForm" inline>
          <el-form-item label="订单编号">
            <el-input
              v-model="saleOrderQueryForm.orderNo"
              placeholder="订单编号"
            ></el-input>
          </el-form-item>
          <el-form-item label="客户名称">
            <el-input
              v-model="saleOrderQueryForm.customerName"
              placeholder="订单客户名称编号"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="getSaleOrderList">搜索</el-button>
            <el-button @click="ResetSaleOrderQueryForm">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
      <el-card>
        <el-table :data="saleOrderList">
          <el-table-column
            v-for="item in saleOrderColumn"
            :key="item.prop"
            :label="item.label"
            :prop="item.prop"
          ></el-table-column>
          <el-table-column v-slot="{ row }">
            <el-button type="primary" @click="SelectSaleOrder(row)"
              >选择</el-button
            >
          </el-table-column>
        </el-table>
        <el-pagination
          style="display: flex; justify-content: right"
          @size-change="SaleOrderLimitChange"
          @current-change="SaleOrderPageChange"
          :current-page="saleOrderPager.page"
          :page-sizes="[5, 10, 30, 40]"
          :page-size="saleOrderPager.limit"
          layout="total, sizes, prev, pager, next, jumper"
          :total="saleOrderPager.total"
        >
        </el-pagination>
      </el-card>
    </el-dialog>

    <!-- 选择物料档案 -->
    <el-dialog
      center
      :visible.sync="materialVisible"
      title="选择物料档案"
      width="1200px"
    >
      <el-row>
        <el-col :span="4">
          <el-tree
            :data="materialCategoryData"
            :props="{ label: 'name' }"
            @node-click="materialCategoryChange"
          ></el-tree>
        </el-col>
        <el-col :span="20">
          <el-table :data="materialData">
            <el-table-column
              v-for="item in materialColumn"
              :key="item.prop"
              :label="item.label"
              :prop="item.prop"
            ></el-table-column>
            <el-table-column label="操作" v-slot="{ row }">
              <el-button type="primary" @click="submitSelectMaterial(row)"
                >选择</el-button
              >
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import { getSaleContractList, EditSaleContract, AddSaleContract, DelSaleContract, getSalesManList } from '@/api_zc/scm/sale-management/sale-contract'
import { getSaleOrderList } from '@/api_zc/scm/sale-management/sale-order'
import { getApplyApproveUserList, getCustomerList } from '@/api_zc/task/sale-order-approve'
import { getMaterialCategoryList, getMaterialList } from '@/api_zc/mes/product-modeling'
import { addSaleDeliveryList } from '@/api_zc/scm/sale-management/sale-delivery'
export default {
  mounted () {
    this.getUnityList()
    this.getSaleContractList()
    this.getSaleOrderList()
    this.getMaterialCategoryList()
    this.getMaterialList()
  },
  data () {
    return {
      customerList: [],
      salesManList: [],
      userList: [],
      saleContractQueryForm: {
        contractNo: '',
        orderId: '',
        salesmanId: '',
        customerId: '',
        deliveryStartDate: '',
        deliveryEndDate: '',
        deliveryAttr: [],
        deliveryMethod: '',
        signStartDate: '',
        signEndDate: '',
        signAttr: [],
        applyUser: '',
        applyStartTime: '',
        applyEndTime: '',
        applyAttr: [],
        applyStatus: '',
        approveUser: '',
        approveStartTime: '',
        approveEndTime: '',
        approveAttr: [],
        approveStatus: '',
      },
      saleContractList: [],
      saleContractPager: {
        page: 1,
        limit: 10,
        total: 0
      },
      isAdd: false,
      saleContractColumn: [
        {
          label: '编号',
          prop: 'id'
        },
        {
          label: '订单编号',
          prop: 'order.orderNo'
        },
        {
          label: '联系人',
          prop: 'contact'
        },
        {
          label: '联系方式',
          prop: 'phone'
        },
        {
          label: '合同金额',
          prop: 'totalAmount'
        },
        {
          label: '交货日期',
          prop: 'deliveryDate'
        },
        {
          label: '申请人',
          prop: 'applyUser.realName'
        },
        {
          label: '申请时间',
          prop: 'applyTime'
        },
        {
          label: '申请状态',
          prop: 'applyStatus'
        },
        {
          label: '审核人',
          prop: 'approveUser.realName'
        },
        {
          label: '审核时间',
          prop: 'approveTime'
        },
        {
          label: '审核状态',
          prop: 'approveStatus'
        },
      ],

      saleOrderList: [],
      saleOrderPager: {
        page: 1,
        limit: 5,
        total: 0
      },
      saleOrderColumn: [
        {
          label: '编号',
          prop: 'id'
        },
        {
          label: '订单编号',
          prop: 'orderNo'
        },
        {
          label: '客户名称',
          prop: 'customer.name'
        },
        {
          label: '金额合计',
          prop: 'totalAmount'
        },
        {
          label: '交货日期',
          prop: 'deliveryDate'
        }
      ],


      saleContractEditDialogVisible: false,
      doEditSaleContractForm: {
        id: '',
        orderNo: '',
        deliveryMethod: '',
        deliveryAddress: '',
        contact: '',
        phone: '',
        signDate: '',
        remark: '',
      },

      detailList: [], //
      detailColumn: [
        {
          label: '型号',
          prop: 'material.model'
        },
        {
          label: '规格',
          prop: 'material.specification'
        },
        {
          label: '单位',
          prop: 'material.unit'
        },
        {
          label: '单价',
          prop: 'price',
          width: '150px'
        },
        {
          label: '订货数量',
          prop: 'quantity',
          width: '150px'
        },
        {
          label: '金额',
          prop: 'amount'
        },
        {
          label: '备注',
          prop: 'remark'
        },
      ],

      saleOrderVisible: false,
      saleOrderQueryForm: {
        orderNo: '',
        customerName: ''
      },
      orderId: 0,
      materialVisible: false,
      materialCategoryData: [],
      materialData: [],
      materialColumn: [
        {
          label: '编号',
          prop: 'id'
        },
        {
          label: '物料编码',
          prop: 'code'
        },
        {
          label: '物料名称',
          prop: 'name'
        },
        {
          label: '型号',
          prop: 'model'
        },
        {
          label: '规格',
          prop: 'specification'
        },
        {
          label: '单位',
          prop: 'unit'
        },
        {
          label: '单价',
          prop: 'price'
        },
        {
          label: '类型',
          prop: 'category.name'
        },
        {
          label: '备注',
          prop: 'remark'
        },
      ],
      materialCategoryPid: 0,
      updateMaterialId: 0,
      title: '',
      deleteIds: []
    }
  },
  methods: {
    async addSaleDeliveryList (id) {
      await addSaleDeliveryList({ id })
      this.$message.success('生成发货单成功')
    },
    async getUnityList () {
      const data1 = await getSalesManList()
      this.salesManList = data1.data
      const data2 = await getApplyApproveUserList()
      this.userList = data2.data
      const { data: { content } } = await getCustomerList()
      this.customerList = content
    },
    async getMaterialCategoryList () {
      const { data } = await getMaterialCategoryList()
      const array = [
        {
          children: data,
          id: 0,
          name: '目录'
        }
      ]
      this.materialCategoryData = array
    },
    async getMaterialList () {
      const { data: { content } } = await getMaterialList({ pid: this.materialCategoryPid })
      this.materialData = content
    },
    resetSaleContractForm () {
      Object.assign(this.saleContractQueryForm, this.$options.data().saleContractQueryForm)
      this.getSaleContractList()
    },
    async getSaleContractList () {

      console.log(this.saleContractQueryForm.deliveryAttr[0]);
      [this.saleContractQueryForm.deliveryStartDate, this.saleContractQueryForm.deliveryEndDate] = this.saleContractQueryForm.deliveryAttr
      [this.saleContractQueryForm.signStartDate, this.saleContractQueryForm.signEndDate] = this.saleContractQueryForm.signAttr
      [this.saleContractQueryForm.applyStartTime, this.saleContractQueryForm.applyEndTime] = this.saleContractQueryForm.applyAttr
      [this.saleContractQueryForm.approveStartTime, this.saleContractQueryForm.approveEndTime] = this.saleContractQueryForm.approveAttr
      const { data: { total, content } } = await getSaleContractList({
        ...this.saleContractQueryForm,
        page: this.saleContractPager.page,
        limit: this.saleContractPager.limit
      })
      this.saleContractList = content
      this.saleContractPager.total = total
    },
    async getSaleOrderList () {
      const { data: { total, content } } = await getSaleOrderList({
        ...this.saleOrderQueryForm,
        page: this.saleOrderPager.page,
        limit: this.saleOrderPager.limit
      })
      this.saleOrderList = content
      this.saleOrderPager.total = total
    },
    SaleContractLimitChange (val) {
      this.saleContractPager.limit = val
      this.getSaleContractList()
    },
    SaleContractPageChange (val) {
      this.saleContractPager.page = val
      this.getSaleContractList()
    },
    SaleOrderLimitChange (val) {
      this.saleOrderPager.limit = val
      this.getSaleOrderList()
    },
    SaleOrderPageChange (val) {
      this.saleOrderPager.page = val
      this.getSaleOrderList()
    },
    OpenEditSaleContractDialog (row) {
      for (let key in row) {
        if (row.hasOwnProperty(key)) {
          if (this.doEditSaleContractForm.hasOwnProperty(key)) {
            this.doEditSaleContractForm[key] = row[key]
          }
        }
      }
      this.doEditSaleContractForm.orderNo = row.order.orderNo
      this.detailList = row.detailList
      this.saleContractEditDialogVisible = true
      this.title = '修改销售合同'
      this.isAdd = false
    },
    OpenAddSaleContractDialog () {
      this.saleContractEditDialogVisible = true
      this.isAdd = true
      this.title = '新增销售合同'
      this.$nextTick(() => {
        this.$refs.doEditSaleContractFormRef.resetFields()
      })
      this.detailList = []
    },
    OpenSaleOrderDialog () {
      this.saleOrderVisible = true
    },
    EditSaleContract () {
      if (!this.orderId) {
        return this.$message.warning('请选择销售订单')
      }
      if (this.isAdd) {
        this.$refs.doEditSaleContractFormRef.validate(async (callback) => {
          if (callback) {
            this.doEditSaleContractForm.signDate = new Date(this.doEditSaleContractForm.signDate)
            const data = { ...this.doEditSaleContractForm, detailList: this.detailList, orderId: this.orderId }
            await AddSaleContract(data)
            this.$message.success('新增成功')
            this.saleContractEditDialogVisible = false
            this.getSaleContractList()
            this.$refs.doEditSaleContractFormRef.resetFields()
          }
        })
        return
      }
      this.$refs.doEditSaleContractFormRef.validate(async (callback) => {
        if (callback) {
          this.doEditSaleContractForm.signDate = new Date(this.doEditSaleContractForm.signDate)
          const data = { ...this.doEditSaleContractForm, detailList: this.detailList, orderId: this.orderId }
          await EditSaleContract(data)
          this.$message.success('修改成功')
          this.saleContractEditDialogVisible = false
          this.getSaleContractList()
        }
      })
    },
    closeEditSaleContractDialog () {
      this.saleContractEditDialogVisible = false
      this.getSaleContractList()
    },
    ResetSaleOrderQueryForm () {
      Object.assign(this.saleOrderQueryForm, this.$options.data().saleOrderQueryForm)
      this.getSaleOrderList()
    },
    SelectSaleOrder (row) {
      this.doEditSaleContractForm.orderNo = row.orderNo
      this.orderId = row.id
      this.saleOrderVisible = false
    },
    SelectMaterial (index) {
      this.materialVisible = true
      this.updateMaterialId = index
    },
    DelDetailList (index) {
      this.detailList.splice(index, 1)
    },
    AddDetailEmpty (index) {
      this.detailList.splice(index + 1, 0, {
        quantity: 1,
        remark: '',
        amount: 0,
        price: 0,
        material: {
          name: '',
          model: '',
          specification: '',
          unit: '',
        },
      })
    },
    AddDetail () {
      this.detailList.push({
        quantity: 1,
        remark: '',
        amount: 0,
        price: 0,
        material: {
          name: '',
          model: '',
          specification: '',
          unit: '',
        },
      })
    },
    submitSelectMaterial (row) {
      row.category = ''
      this.detailList[this.updateMaterialId].material = row
      this.materialVisible = false
    },
    materialCategoryChange ({ id }) {
      this.materialCategoryPid = id
      this.getMaterialList()
    },
    DelSaleContractMany () {
      if (!this.deleteIds.length) {
        return
      }
      this.$confirm(`是否确认删除销售合同编号为${this.deleteIds.join(',')}的数据项`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.DelSaleContract(this.deleteIds)
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    async DelSaleContract (ids) {
      await DelSaleContract({ ids })
      this.$message.success('删除成功')
      this.getSaleContractList()
    },
    DelSaleContractD (id) {
      this.$confirm(`是否确认删除销售合同编号为${id}的数据项`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.DelSaleContract([id])
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    selectionChange (row) {
      this.deleteIds = row.map(item => { return item.id })
    }
  }
}
</script>